﻿using System;
using System.Collections.Generic;

namespace GxFramework
{
    public static class DictionaryPool<TK,TV>
    {
        static int _countAll;
        static readonly Stack<Dictionary<TK, TV>> _stack = new Stack<Dictionary<TK, TV>>();

        static public int countAll { get { return _countAll; } }
        static public int countActive { get { return countAll - countInactive; } }
        static public int countInactive { get { return _stack.Count; } }
        static public Dictionary<TK, TV> Get(IEqualityComparer<TK> comparer=null, int capacity = 0)
        {
            Dictionary<TK, TV> ret = null;
            if (_stack.Count == 0)
            {
                if (null == comparer)
                    ret = new Dictionary<TK, TV>(capacity);
                else
                    ret = new Dictionary<TK, TV>(capacity,comparer);
                ++_countAll;
            }
            else
                ret = _stack.Pop();
            return ret;
        }
        static public void Release(Dictionary<TK, TV> item)
        {
            if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), item))
                throw new Exception("[DictionaryPool] Internal error. Trying to release Dictionary that is already released to pool.");
            item.Clear();
            _stack.Push(item);
        }
        static public void Put(Dictionary<TK, TV> item)
        {
            if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), item))
                throw new Exception("[DictionaryPool] Internal error. Trying to put Dictionary that is already released to pool.");
            _stack.Clear();
            _stack.Push(item);
            ++_countAll;
        }
        static public void Clear()
        {
            _stack.Clear();
            _countAll = 0;
        }
        static public void Clear(int reserveCount)
        {
            while (_stack.Count > reserveCount)
            {
                --_countAll;
                var item = _stack.Pop();
                item.Clear();
            }
        }
    }
}
